package com.leyou.item.web;

import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;


    /**
     * 分页查询spu
     *
     * @param page
     * @param rows
     * @param saleable
     * @param key
     * @return
     */
    @GetMapping("/spu/page")
    public ResponseEntity<PageResult<Spu>> querySpuByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,//当前页
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,//每页条数
            @RequestParam(value = "saleable", required = false) Boolean saleable,//过滤条件是否上下架
            @RequestParam(value = "key", required = false) String key//搜索条件
    ) {

        PageResult<Spu> spuPageResult = goodsService.querySpuByPage(page, rows, saleable, key);

        return ResponseEntity.ok().body(spuPageResult);
    }

    /**
     * 保存spu
     * @param spu
     * @return
     */
    @PostMapping("/goods")
    public ResponseEntity<Void> saveGoods(@RequestBody Spu spu) {

        goodsService.saveGoods(spu);


        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    /**
     * 更新商品
     * @param spu
     * @return
     */
    @PutMapping("/goods")
    public ResponseEntity<Void> updateGoods(@RequestBody Spu spu){
        goodsService.updateGoods(spu);

        return ResponseEntity.ok().build();

    }

    /**
     * 根据spuid查询spu详情
     * @param spuId
     * @return
     */
    @GetMapping("/spu/detail/{id}")
    public ResponseEntity<SpuDetail> querySpuDetailById(@PathVariable("id") Long spuId){


        return ResponseEntity.ok(goodsService.querySpuDetailById(spuId));
    }

    /**
     * 根据spuid查询所有sku
     * @param spuId
     * @return
     */
    @GetMapping("/sku/list")
    public ResponseEntity<List<Sku>> querySkuBySpuId(@RequestParam("id") Long spuId){

        return ResponseEntity.ok(goodsService.querySkuBySpuId(spuId));
    }

    @GetMapping("spu/{id}")
    public ResponseEntity<Spu> querySpuById(@PathVariable("id") Long id){

        return ResponseEntity.ok(goodsService.querySpuById(id));

    }

    @GetMapping("sku/{skuId}")
    public ResponseEntity<Sku> querySkuById(@PathVariable("skuId") Long skuId){

       Sku sku=goodsService.querySkuById(skuId);
       return ResponseEntity.ok(sku);
    }


}
